<template>
  <view class="container">

    <!-- 发布说明卡片 -->
    <view class="info-card welcome-card">
      <view class="welcome-header">
        <u-icon name="edit-pen" color="#0ea5e9" size="32"></u-icon>
        <text class="welcome-title">发布招聘信息</text>
      </view>
      <text class="welcome-desc">请填写详细的招聘信息，优质的职位描述能够吸引更多优秀人才。</text>
    </view>

    <!-- 基础信息表单 -->
    <view class="info-card form-card">
      <view class="section-title">
        <u-icon name="info-circle" color="#0ea5e9" size="18"></u-icon>
        <text class="title-text">职位基础信息</text>
      </view>

      <u--form :model="formData" ref="uForm" :rules="rules" label-width="100px">
        <u-form-item label="职位名称" prop="title" required>
          <u-input v-model="formData.title" placeholder="如：招聘服务员" border="surround"></u-input>
        </u-form-item>

        <u-form-item label="公司名称" prop="company" required>
          <u-input v-model="formData.company" placeholder="如：喜桥酒楼" border="surround"></u-input>
        </u-form-item>

        <u-form-item label="工作地点" prop="location" required>
          <u-input v-model="formData.location" placeholder="如：凯通路45号" border="surround"></u-input>
          <view slot="right" style="margin-left: 10px;">
            <u-button @click="handleCheckLocation">选择</u-button>
          </view>
        </u-form-item>

        <u-form-item label="薪资范围" prop="salaryRange" required>
          <u-input v-model="formData.salaryRange" placeholder="例如：2K-5K" border="surround"></u-input>
        </u-form-item>

        <u-form-item label="学历要求" prop="education" required>
          <u-input v-model="formData.education" placeholder="请选择学历要求" border="surround" :disabled="true"></u-input>
          <view slot="right" style="margin-left: 10px;">
            <u-button @click="showEducationPicker">选择</u-button>
          </view>
        </u-form-item>

        <u-form-item label="工作经验" prop="experience" required>
          <u-input v-model="formData.experience" placeholder="请选择工作经验" border="surround" :disabled="true"></u-input>
          <view slot="right" style="margin-left: 10px;">
            <u-button @click="showExperiencePicker">选择</u-button>
          </view>
        </u-form-item>
        <u-form-item label="工作类型" prop="jobType" required>
          <u-input v-model="formData.jobType" placeholder="请选择工作类型" border="surround" :disabled="true"></u-input>
          <view slot="right" style="margin-left: 10px;">
            <u-button @click="showTypePicker">选择</u-button>
          </view>
        </u-form-item>
      </u--form>
    </view>

    <!-- 职位标签 -->
    <view class="info-card form-card">
      <view class="section-title">
        <u-icon name="tags" color="#10b981" size="18"></u-icon>
        <text class="title-text">公司福利</text>
      </view>
      <view class="tags-section">
        <template v-for="item in selectedTags">
          <u-tag :text="item" :key="item" shape="circle" plain type="primary"></u-tag>
        </template>
      </view>
      <view class="tags-section">
        <u-tag v-for="tag in availableTags" :key="tag" type="info" plain :text="tag" shape="circle" @click="toggleTag(tag)"></u-tag>
      </view>
      <view class="custom-tag-input" v-if="showCustomTagInput">
        <u-input v-model="customTag" placeholder="输入自定义标签" border="surround" @confirm="addCustomTag">
          <template slot="suffix">
            <u-button @tap="addCustomTag" text="确定" type="success" size="mini"></u-button>
          </template>
        </u-input>
      </view>
      <u-button type="info" plain @click="toggleCustomTagInput">
        {{ showCustomTagInput ? '取消' : '添加自定义标签' }}
      </u-button>
    </view>

    <!-- 职位描述 -->
    <view class="info-card form-card">
      <view class="section-title">
        <u-icon name="file-text" color="#f59e0b" size="18"></u-icon>
        <text class="title-text">职位描述</text>
      </view>

      <view class="description-section">
        <text class="field-label">岗位职责</text>
        <u-textarea v-model="formData.responsibilities" placeholder="请详细描述岗位职责和工作内容，如：负责收拾碗筷，打扫卫生。" :maxlength="500" count height="200"></u-textarea>
      </view>

      <view class="description-section">
        <text class="field-label">任职要求</text>
        <u-textarea v-model="formData.requirements" placeholder="请详细描述任职要求和技能要求，如：限男性，年龄25-40岁。" :maxlength="500" count height="200"></u-textarea>
      </view>
    </view>

    <!-- 联系信息 -->
    <view class="info-card form-card">
      <view class="section-title">
        <u-icon name="phone" color="#ef4444" size="18"></u-icon>
        <text class="title-text">联系信息</text>
        <u-icon name="plus-circle" @click="handleAddPhone"></u-icon>
      </view>

      <u--form :model="formData" ref="uForm2" label-width="180">
        <template v-for="(item,index) in phoneNumbers">
          <u-form-item :label="`联系人 ${index+1}` " required>
            <u-input v-model="item.name" placeholder="姓名" border="surround"></u-input>
          </u-form-item>
          <u-form-item label="电话" required>
            <u-input v-model="item.phone" placeholder="联系电话" type="number" border="surround"></u-input>
          </u-form-item>
        </template>
      </u--form>
    </view>

    <!-- 公司图片上传 -->
    <view class="info-card form-card" v-if="false">
      <view class="section-title">
        <u-icon name="camera" color="#8b5cf6" size="18"></u-icon>
        <text class="title-text">公司图片</text>
      </view>
      <view class="upload-section">
        <text class="upload-desc">上传公司Logo或办公环境图片（可选）</text>
        <view class="upload-grid">
          <view class="upload-item" v-for="(image, index) in uploadedImages" :key="index">
            <u-image :src="image" width="200rpx" height="200rpx" border-radius="16rpx" mode="aspectFill"></u-image>
            <view class="delete-btn" @click="deleteImage(index)">
              <u-icon name="close" color="#fff" size="12"></u-icon>
            </view>
          </view>
          <view class="upload-placeholder" v-if="uploadedImages.length < 3" @click="chooseImage">
            <u-icon name="plus" color="#94a3b8" size="32"></u-icon>
            <text class="upload-text">添加图片</text>
          </view>
        </view>
      </view>
    </view>


    <!-- 底部操作栏 -->
    <view class="bottom-action-bar">
      <u-button type="info" :plain="true" shape="circle" :custom-style="draftBtnStyle" @click="saveDraft">
        保存草稿
      </u-button>
      <u-button type="primary" shape="circle" :custom-style="publishBtnStyle" @click="handleSave" :loading="loading">
        {{ loading ? '发布中...' : '立即发布' }}
      </u-button>
    </view>

    <!-- 提示组件 -->
    <u-toast ref="uToast"></u-toast>
  </view>
</template>

<script>
  export default {
    data() {
      return {
        loading: false,
        showCustomTagInput: false,
        customTag: '',

        formData: {
          company: '', // 公司名称
          contactPerson: '', // 联系人
          education: '不限', // 学历要求
          experience: '不限', // 经验要求
          face: '', // 公司头像
          jobType: '全职', // 职位类型
          location: '', // 工作地点
          phone: '', // 联系电话 
          requirements: '', // 任职要求
          responsibilities: '', // 岗位职责
          salaryRange: '', // 薪资范围 
          tagsJson: '', // 标签
          addressName: '', // 地址名称
          position: '', // 空间位置
          title: '' // 职位名称
        },
        phoneNumbers: [],
        selectedTags: [],
        uploadedImages: [],

        // 表单验证规则
        rules: {
          title: [
            { required: true, message: '请输入职位名称', trigger: 'blur' }
          ],
          company: [
            { required: true, message: '请输入公司名称', trigger: 'blur' }
          ],
          location: [
            { required: true, message: '请输入工作地点', trigger: 'blur' }
          ],
          salaryRange: [
            { required: true, message: '请输入薪资范围', trigger: 'blur' }
          ],
          education: [
            { required: true, message: '请选择学历要求', trigger: 'change' }
          ],
          experience: [
            { required: true, message: '请选择工作经验', trigger: 'change' }
          ],
          contactPerson: [
            { required: true, message: '请输入联系人姓名', trigger: 'blur' }
          ],
          phone: [
            { required: true, message: '请输入联系电话', trigger: 'blur' },
            { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
          ]
        },
        experienceOptions: ['不限', '应届生', '1年以下', '1-3年', '3-5年', '5-10年', '10年以上'],
        availableTags: ['包吃', '包住', '包吃住', '交社保', '月休4天'],

        draftBtnStyle: {
          flex: '1',
          marginRight: '24rpx',
          height: '88rpx',
          fontSize: '32rpx'
        },
        publishBtnStyle: {
          flex: '1',
          background: 'linear-gradient(135deg, #0ea5e9, #06b6d4)',
          border: 'none',
          height: '88rpx',
          fontSize: '32rpx'
        }
      }
    },
    onLoad() {
      try {
        const draft = uni.getStorageSync('job_draft');
        if (draft) {
          uni.showModal({
            title: '发现草稿',
            content: '是否恢复之前保存的草稿？',
            success: (res) => {
              if (res.confirm) {
                this.formData = { ...draft };
                this.selectedTags = draft.tagsJson ? JSON.parse(draft.tagsJson) : [];
                if (draft.face) {
                  this.uploadedImages = [draft.face];
                }
                if (draft.phoneNumbers) {
                  this.phoneNumbers = draft.phoneNumbers;
                }
              }
            }
          });
        }
      } catch (error) {
        console.error('恢复草稿失败:', error);
      }
    },

    methods: {
      // 显示学历选择器
      showEducationPicker() {
        let list = ['不限', '小学', '初中', '高中', '专科', '本科']
        uni.showActionSheet({
          itemList: list,
          success: (res) => {
            this.formData.education = list[res.tapIndex]
          }
        })
      },
      // 显示经验选择器
      showExperiencePicker() {
        uni.showActionSheet({
          itemList: this.experienceOptions,
          success: (res) => {
            this.formData.experience = this.experienceOptions[res.tapIndex]
          }
        })
      },
      // 显示类型选择器
      showTypePicker() {
        let list = ['全职', '兼职', '实习']
        uni.showActionSheet({
          itemList: list,
          success: (res) => {
            this.formData.jobType = list[res.tapIndex]
          }
        })
      },
      handleCheckLocation() {
        uni.chooseLocation({
          latitude: this.formData.lat || 26.086244,
          longitude: this.formData.lng || 103.182078,
          success: (res) => {
            this.formData.location = res.address
            this.formData.addressName = res.name
            this.formData.lat = res.latitude
            this.formData.lng = res.longitude
            this.formData.position = `[${res.longitude},${res.latitude}]`
            // console.log(res)
          }
        })
      },
      // 切换标签选择
      toggleTag(tag) {
        const index = this.selectedTags.indexOf(tag);
        if (index > -1) {
          this.selectedTags.splice(index, 1);
        } else {
          if (this.selectedTags.length < 8) {
            this.selectedTags.push(tag);
          } else {
            this.$refs.uToast.show({
              title: '最多只能选择8个标签',
              type: 'warning'
            });
          }
        }
      },

      // 切换自定义标签输入
      toggleCustomTagInput() {
        this.showCustomTagInput = !this.showCustomTagInput;
        if (!this.showCustomTagInput) {
          this.customTag = '';
        }
      },

      // 添加自定义标签
      addCustomTag() {
        if (this.customTag.trim() && !this.selectedTags.includes(this.customTag.trim())) {
          if (this.selectedTags.length < 8) {
            this.selectedTags.push(this.customTag.trim());
            this.customTag = '';
            this.showCustomTagInput = false;
          } else {
            this.$refs.uToast.show({
              message: '最多只能选择8个标签',
              type: 'warning'
            });
          }
        }
      },

      // 选择图片
      chooseImage() {
        uni.chooseImage({
          count: 3 - this.uploadedImages.length,
          sizeType: ['compressed'],
          sourceType: ['album', 'camera'],
          success: (res) => {
            this.uploadedImages = this.uploadedImages.concat(res.tempFilePaths);
          }
        });
      },
      handleAddPhone() {
        let item = {
          name: '',
          phone: ''
        }
        if (this.phoneNumbers.length > 2) {
          return
        }
        this.phoneNumbers.push(item)
      },
      // 删除图片
      deleteImage(index) {
        this.uploadedImages.splice(index, 1);
      },

      // 保存草稿
      async saveDraft() {
        try {
          const draftData = {
            ...this.formData,
            tagsJson: JSON.stringify(this.selectedTags),
            face: this.uploadedImages[0] || '',
            phoneNumbers: this.phoneNumbers
          }
          console.log('保存草稿:', draftData);

          // 模拟保存到本地存储
          uni.setStorageSync('job_draft', draftData);

          this.$refs.uToast.show({
            message: '草稿保存成功',
            type: 'success'
          });

        } catch (error) {
          console.error('保存草稿失败:', error);
          this.$refs.uToast.show({
            message: '保存失败，请重试',
            type: 'error'
          });
        }
      },

      // 发布招聘
      async handleSave() {
        try {
          // 表单验证
          const valid = await this.validateForm();
          if (!valid) return;

          this.loading = true;

          // 构建提交数据
          const model = {
            ...this.formData,
            tagsJson: JSON.stringify(this.selectedTags),
            face: this.uploadedImages[0] || '',
            phoneNumbers: JSON.stringify(this.phoneNumbers)
          }
          // console.log('发布数据:', model);
          uni.$u.http.post('/api/zhaopin/publish', model).then(response => {
            let { code, result, message } = response.data
            if (code != 200) {
              this.$refs.uToast.show({
                message: message,
                type: 'error'
              });
              return
            }
            uni.showModal({
              title: '发布成功',
              content: `你已成功发布：${model.title}`,
              success: (res) => {
                this.$u.route({ type: 'back' })
                if (res.cancel) {
                  return
                }
                // 清除草稿
                uni.removeStorageSync('job_draft');
              }
            })

          })

        } catch (error) {
          console.error('发布失败:', error);
          this.$refs.uToast.show({
            message: '发布失败，请重试',
            type: 'error'
          });
        } finally {
          this.loading = false;
        }
      },

      // 表单验证
      async validateForm() {
        try {
          // 基础信息验证
          await this.$refs.uForm.validate();
          await this.$refs.uForm2.validate();

          // 职位描述验证
          if (!this.formData.requirements.trim()) {
            this.$refs.uToast.show({
              title: '请填写任职要求',
              type: 'warning'
            });
            return false;
          }

          return true;
        } catch (error) {
          console.error('表单验证失败:', error);
          return false;
        }
      }
    }
  }
</script>

<style lang="scss" scoped>
  .container {
    min-height: 100vh;
    background: #f8fafc;
    display: flex;
    flex-direction: column;
  }

  .info-card {
    background: white;
    border-radius: 24rpx;
    margin: 0 10rpx 10rpx;
    padding: 32rpx;
    box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.08);
    border: 1rpx solid #f1f5f9;
  }

  .welcome-card {
    margin-top: 24rpx;

    .welcome-header {
      display: flex;
      align-items: center;
      gap: 16rpx;
      margin-bottom: 16rpx;

      .welcome-title {
        font-size: 32rpx;
        font-weight: 600;
        color: #1e293b;
      }
    }

    .welcome-desc {
      font-size: 26rpx;
      color: #64748b;
      line-height: 1.5;
    }
  }

  .section-title {
    display: flex;
    align-items: center;
    gap: 12rpx;
    font-size: 28rpx;
    font-weight: 600;
    color: #1e293b;
    margin-bottom: 32rpx;
  }

  .tags-section {
    display: flex;
    flex-wrap: wrap;
    margin-bottom: 16rpx;
    gap: 10upx;
  }

  .custom-tag-input {
    margin-bottom: 16rpx;
  }

  .description-section {
    margin-bottom: 32rpx;

    &:last-child {
      margin-bottom: 0;
    }

    .field-label {
      font-size: 28rpx;
      font-weight: 500;
      color: #334155;
      margin-bottom: 16rpx;
      display: block;
    }
  }

  .upload-section {
    .upload-desc {
      font-size: 26rpx;
      color: #64748b;
      margin-bottom: 24rpx;
      display: block;
    }

    .upload-grid {
      display: flex;
      flex-wrap: wrap;
      gap: 24rpx;

      .upload-item {
        position: relative;

        .delete-btn {
          position: absolute;
          top: -12rpx;
          right: -12rpx;
          width: 48rpx;
          height: 48rpx;
          background: #ef4444;
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          box-shadow: 0 4rpx 12rpx rgba(239, 68, 68, 0.3);
        }
      }

      .upload-placeholder {
        width: 200rpx;
        height: 200rpx;
        background: #f8fafc;
        border: 2rpx dashed #cbd5e1;
        border-radius: 16rpx;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        gap: 12rpx;

        .upload-text {
          font-size: 24rpx;
          color: #94a3b8;
        }
      }
    }
  }

  .bottom-space {
    height: 40rpx;
  }

  .bottom-action-bar {
    background: white;
    display: flex;
    gap: 24rpx;
    padding: 24rpx 32rpx;
    border-top: 1rpx solid #f1f5f9;
    box-shadow: 0 -4rpx 20rpx rgba(0, 0, 0, 0.06);
  }
</style>